import {KPlayerStatus} from '../@types/player'
import KUnit from '@kernel/util/unit'
import Cache from '@kernel/util/cache'
import AbstractData from '@kernel/interfaces/AbstractData'

const cache = new Cache()

let handle = 0

/**
 * 玩家.
 */
export default class KPlayer extends AbstractData {
  public handle: Role;
  public handleId;

  constructor(role: Role) {
    super()
    this.handleId = handle++
    this.handle = role
  }

  /**
   * 根据玩家id获取玩家实例
   * @param id
   */
  static fromId(id: RoleID): KPlayer {
    const role = gameapi.get_role_by_role_id(id)
    return cache.get('player:' + id, () => new KPlayer(role))
  }

  /**
   * 根据role获取玩家实例
   */
  static fromRole(role: Role): KPlayer {
    return cache.get('player:' + role.api_get_role_id(), () => new KPlayer(role))
  }

  /**
   * 本地玩家
   */
  static fromLocal(): KPlayer {
    const role = gameapi.get_client_role()
    return cache.get('player:' + role.api_get_role_id(), () => new KPlayer(role))
  }

  /**
   * 玩家id.
   */
  get id(): number {
    return <number>this.handle.get_role_id_num()
  }

  /**
   * 队伍id.
   */
  get campId(): number {
    return <number>this.handle.get_camp_id_num()
  }

  /**
   * 队伍.
   */
  get camp(): Camp {
    return this.handle.api_get_camp()
  }

  /**
   * 名称.
   */
  get name(): string {
    return <string>this.handle.get_role_name()
  }

  /**
   * 游戏状态.
   */
  get status(): KPlayerStatus {
    const value = this.handle.get_role_status()
    if (value == 1) {
      return KPlayerStatus.Playing
    }
    return KPlayerStatus.Offline
  }

  /**
   * 设置鼠标点选状态.
   */
  public setMouseClickSelection (status: boolean) {
    this.handle.set_role_mouse_left_click(status)
  }

  /**
   * 设置鼠标框选状态.
   */
  public setMouseMoveSelection (status: boolean) {
    this.handle.set_role_mouse_move_select(status)
  }

  /**
   * 设置鼠标滚轮状态.
   */
  public setMouseWheel (status: boolean) {
    this.handle.set_role_mouse_wheel(status)
  }

  /**
   * 玩家实例销毁.
   */
  public destroy() {
    this.data.clear()
  }

  /**
   * 选择单位
   * @param target
   */
  selectUnit(target: KUnit) {
    this.handle.role_select_unit(target.handle)
  }
}
